/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SessionEditor.java
 *
 * Created on 23-Sep-2011, 12:15:00
 */

package TimeRecording.forms;

import TimeRecording.business.DaisyChainUtilities;
import TimeRecording.tables.Session;
import TimeRecording.widgets.EmployeeComboBox;
import java.awt.CardLayout;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Date;
import javax.swing.JOptionPane;
import org.jdesktop.application.Action;

/**
 *
 * @author david
 */
public class SessionEditor extends javax.swing.JDialog {

    private static final String HOURS_PANEL = "Hours Panel";
    private static final String TIME_FRAME_PANEL = "Time Frame Panel";

    /** Creates new form SessionEditor */
    public SessionEditor(SessionsDialog parent) {
        super(parent, ModalityType.APPLICATION_MODAL);
        myParent = parent;
        initComponents();
    }

    // <editor-fold defaultstate="collapsed" desc="Property Change Support">
    private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);

    @Override
    public void addPropertyChangeListener(PropertyChangeListener listener) {
	changeSupport.addPropertyChangeListener(listener);
    }

    @Override
    public void removePropertyChangeListener(PropertyChangeListener listener) {
	changeSupport.removePropertyChangeListener(listener);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="transientSession + Getter & Setter">
    private Session transientSession = new Session();

    public Session getTransientSession() {
        return transientSession;
    }

    public void setTransientSession(Session transientSession) {
        Session oldTransientSession = this.transientSession;
        this.transientSession = transientSession;
        changeSupport.firePropertyChange("transientSession", oldTransientSession, transientSession);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="persistentSession + Getter & Setter">
    private Session persistentSession;

    public Session getPersistentSession() {
        return persistentSession;
    }

    public void setPersistentSession(Session persistentSession) {
        Session oldPersistentSession = this.persistentSession;
        this.persistentSession = persistentSession;
        changeSupport.firePropertyChange("persistentSession", oldPersistentSession, persistentSession);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="saveSelected + Getter & Setter">
    private boolean saveSelected;

    public boolean isSaveSelected() {
        return saveSelected;
    }

    public void setSaveSelected(boolean saveSelected) {
        boolean oldSaveSelected = this.saveSelected;
        this.saveSelected = saveSelected;
        changeSupport.firePropertyChange("saveSelected", oldSaveSelected, saveSelected);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="hoursSpecified + Getter & Setter">
    private boolean hoursSpecified;
    
    public boolean getHoursSpecified() {
        return hoursSpecified;
        
    }
    public void setHoursSpecified(boolean hoursSpecified) {
        boolean oldHoursSpecified = this.hoursSpecified;
        this.hoursSpecified = hoursSpecified;
        firePropertyChange("hoursSpecified", oldHoursSpecified, hoursSpecified);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="timeFrameSpecified + Getter & Setter">
    private boolean timeFrameSpecified;

    public boolean getTimeFrameSpecified() {
        return timeFrameSpecified;

    }
    public void setTimeFrameSpecified(boolean timeFrameSpecified) {
        boolean oldTimeFrameSpecified = this.timeFrameSpecified;
        this.timeFrameSpecified = timeFrameSpecified;
        firePropertyChange("timeFrameSpecified", oldTimeFrameSpecified, timeFrameSpecified);
    } // </editor-fold>

    public void setSession(Session session) {

        setPersistentSession(session);
        transientSession.copy(session);

        // Would have been nice to achieve the job of the following two lines
        // using the bound variables but it doesn't seem to work and doesn't
        // seem to be worth wasting time on when there is a work-around.

        numberOfHoursRadioButton.setSelected(
                session.getHours() != null && session.getHours() > 0);
        
        timeFrameRadioButton.setSelected(
                session.getHours() == null || session.getHours() == 0);

        hoursOrTimeFrameChanged(null);

        Date tempDate;
        if (transientSession.getStartTime() == null) {
            tempDate = new Date();
        } else {
            tempDate = (Date) transientSession.getStartTime().clone();
        }
        DaisyChainUtilities.cleanDate(tempDate);
        date.setDate(tempDate);
        
        startTime.setTimeAsDouble(DaisyChainUtilities.
                getTimeOnlyAsDouble(transientSession.getStartTime()));

        endTime.setTimeAsDouble(DaisyChainUtilities.
                getTimeOnlyAsDouble(transientSession.getEndTime()));
    }

    /** This method is called from within the constructor to
     * initialise the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = myParent.getEntityManager();
        dateConverter = new TimeRecording.widgets.DateConverter();
        timeSpecificationGroup = new javax.swing.ButtonGroup();
        holidayRequestDetails = new javax.swing.JPanel();
        employeeLabel = new javax.swing.JLabel();
        employee = new EmployeeComboBox(entityManager);
        commentLabel = new javax.swing.JLabel();
        comment = new javax.swing.JTextField();
        adjustmentDateLabel = new javax.swing.JLabel();
        date = new com.toedter.calendar.JDateChooser();
        hoursOrTimeFramePanel = new javax.swing.JPanel();
        absoluteHoursPanel = new javax.swing.JPanel();
        hoursLabel = new javax.swing.JLabel();
        hours = new javax.swing.JTextField();
        timeFramePanel = new javax.swing.JPanel();
        startTimeLabel = new javax.swing.JLabel();
        startTime = new TimeRecording.widgets.TimeTextField();
        endTimeLabel = new javax.swing.JLabel();
        endTime = new TimeRecording.widgets.TimeTextField();
        buttonPanel = new javax.swing.JPanel();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        hoursOrTimeSelectionPanel = new javax.swing.JPanel();
        numberOfHoursRadioButton = new javax.swing.JRadioButton();
        timeFrameRadioButton = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(TimeRecording.TimeRecordingApp.class).getContext().getResourceMap(SessionEditor.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));

        holidayRequestDetails.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 8, 4, 8));
        holidayRequestDetails.setName("holidayRequestDetails"); // NOI18N
        holidayRequestDetails.setLayout(new java.awt.GridBagLayout());

        employeeLabel.setText(resourceMap.getString("employeeLabel.text")); // NOI18N
        employeeLabel.setName("employeeLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(8, 4, 4, 4);
        holidayRequestDetails.add(employeeLabel, gridBagConstraints);

        employee.setName("employee"); // NOI18N
        employee.setPreferredSize(new java.awt.Dimension(150, 20));

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${transientSession.employeeId}"), employee, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${administratorEditable}"), employee, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(8, 4, 4, 8);
        holidayRequestDetails.add(employee, gridBagConstraints);

        commentLabel.setText(resourceMap.getString("commentLabel.text")); // NOI18N
        commentLabel.setName("commentLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        holidayRequestDetails.add(commentLabel, gridBagConstraints);

        comment.setName("comment"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${transientSession.description}"), comment, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${administratorEditable}"), comment, org.jdesktop.beansbinding.BeanProperty.create("editable"));
        bindingGroup.addBinding(binding);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        holidayRequestDetails.add(comment, gridBagConstraints);

        adjustmentDateLabel.setText(resourceMap.getString("adjustmentDateLabel.text")); // NOI18N
        adjustmentDateLabel.setName("adjustmentDateLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        holidayRequestDetails.add(adjustmentDateLabel, gridBagConstraints);

        date.setMinimumSize(new java.awt.Dimension(150, 20));
        date.setName("date"); // NOI18N
        date.setPreferredSize(new java.awt.Dimension(80, 20));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${date}"), date, org.jdesktop.beansbinding.BeanProperty.create("date"));
        bindingGroup.addBinding(binding);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        holidayRequestDetails.add(date, gridBagConstraints);

        hoursOrTimeFramePanel.setName("hoursOrTimeFramePanel"); // NOI18N
        hoursOrTimeFramePanel.setLayout(new java.awt.CardLayout());

        absoluteHoursPanel.setName("absoluteHoursPanel"); // NOI18N
        absoluteHoursPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 10, 5));

        hoursLabel.setText(resourceMap.getString("hoursLabel.text")); // NOI18N
        hoursLabel.setName("hoursLabel"); // NOI18N
        absoluteHoursPanel.add(hoursLabel);

        hours.setMinimumSize(new java.awt.Dimension(100, 20));
        hours.setName("hours"); // NOI18N
        hours.setPreferredSize(new java.awt.Dimension(100, 20));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${transientSession.hours}"), hours, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        absoluteHoursPanel.add(hours);

        hoursOrTimeFramePanel.add(absoluteHoursPanel, "Hours Panel");

        timeFramePanel.setName("timeFramePanel"); // NOI18N
        timeFramePanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 10, 5));

        startTimeLabel.setText(resourceMap.getString("startTimeLabel.text")); // NOI18N
        startTimeLabel.setName("startTimeLabel"); // NOI18N
        timeFramePanel.add(startTimeLabel);

        startTime.setMinimumSize(new java.awt.Dimension(100, 20));
        startTime.setName("startTime"); // NOI18N
        startTime.setPreferredSize(new java.awt.Dimension(100, 20));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${startMinutes}"), startTime, org.jdesktop.beansbinding.BeanProperty.create("timeAsDouble"));
        bindingGroup.addBinding(binding);

        timeFramePanel.add(startTime);

        endTimeLabel.setText(resourceMap.getString("endTimeLabel.text")); // NOI18N
        endTimeLabel.setName("endTimeLabel"); // NOI18N
        timeFramePanel.add(endTimeLabel);

        endTime.setMinimumSize(new java.awt.Dimension(100, 20));
        endTime.setName("endTime"); // NOI18N
        endTime.setPreferredSize(new java.awt.Dimension(100, 20));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${endMinutes}"), endTime, org.jdesktop.beansbinding.BeanProperty.create("timeAsDouble"));
        bindingGroup.addBinding(binding);

        timeFramePanel.add(endTime);

        hoursOrTimeFramePanel.add(timeFramePanel, "Time Frame Panel");

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        holidayRequestDetails.add(hoursOrTimeFramePanel, gridBagConstraints);

        buttonPanel.setName("buttonPanel"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(TimeRecording.TimeRecordingApp.class).getContext().getActionMap(SessionEditor.class, this);
        saveButton.setAction(actionMap.get("saveClicked")); // NOI18N
        saveButton.setText(resourceMap.getString("saveButton.text")); // NOI18N
        saveButton.setName("saveButton"); // NOI18N
        buttonPanel.add(saveButton);

        cancelButton.setAction(actionMap.get("cancelClicked")); // NOI18N
        cancelButton.setText(resourceMap.getString("cancelButton.text")); // NOI18N
        cancelButton.setName("cancelButton"); // NOI18N
        buttonPanel.add(cancelButton);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        holidayRequestDetails.add(buttonPanel, gridBagConstraints);

        hoursOrTimeSelectionPanel.setName("hoursOrTimeSelectionPanel"); // NOI18N

        timeSpecificationGroup.add(numberOfHoursRadioButton);
        numberOfHoursRadioButton.setText(resourceMap.getString("numberOfHoursRadioButton.text")); // NOI18N
        numberOfHoursRadioButton.setName("numberOfHoursRadioButton"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${hoursSpecified}"), numberOfHoursRadioButton, org.jdesktop.beansbinding.BeanProperty.create("selected"));
        bindingGroup.addBinding(binding);

        numberOfHoursRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hoursOrTimeFrameChanged(evt);
            }
        });
        hoursOrTimeSelectionPanel.add(numberOfHoursRadioButton);

        timeSpecificationGroup.add(timeFrameRadioButton);
        timeFrameRadioButton.setText(resourceMap.getString("timeFrameRadioButton.text")); // NOI18N
        timeFrameRadioButton.setName("timeFrameRadioButton"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${timeFrameSpecified}"), timeFrameRadioButton, org.jdesktop.beansbinding.BeanProperty.create("selected"));
        bindingGroup.addBinding(binding);

        timeFrameRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hoursOrTimeFrameChanged(evt);
            }
        });
        hoursOrTimeSelectionPanel.add(timeFrameRadioButton);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        holidayRequestDetails.add(hoursOrTimeSelectionPanel, gridBagConstraints);

        getContentPane().add(holidayRequestDetails);

        bindingGroup.bind();

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-463)/2, (screenSize.height-242)/2, 463, 242);
    }// </editor-fold>//GEN-END:initComponents

    @Action
    private void hoursOrTimeFrameChanged(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hoursOrTimeFrameChanged

        CardLayout layout = (CardLayout)hoursOrTimeFramePanel.getLayout();

        if (hoursSpecified) {
            layout.show(hoursOrTimeFramePanel, HOURS_PANEL);
        }
        if (timeFrameSpecified) {
            layout.show(hoursOrTimeFramePanel, TIME_FRAME_PANEL);
        }
    }//GEN-LAST:event_hoursOrTimeFrameChanged

    private boolean validateSession() {
        
        if (transientSession.getEmployeeId() == null ||
                date.getDate() == null) {

            JOptionPane.showMessageDialog(this,
                    "Insufficient details supplied",
                    "Save Session",
                    JOptionPane.ERROR_MESSAGE);

            return false;
        }

        if (timeFrameSpecified) {
            transientSession.setStartTime(DaisyChainUtilities.glueDateAndTime(
                    date.getDate(), startTime.getTimeAsDouble()));
            
            transientSession.setEndTime(DaisyChainUtilities.glueDateAndTime(
                    date.getDate(), endTime.getTimeAsDouble()));
            
            transientSession.setHours(endTime.getTimeAsDouble() - startTime.getTimeAsDouble());

        } else {

            transientSession.setStartTime(date.getDate());
            transientSession.setEndTime(null);
        }
        
        return true;
    }

    @Action
    public void cancelClicked() {
        setSaveSelected(false);
        setVisible(false);
    }

    @Action
    public void saveClicked() {

        if (!validateSession()) {
            return;
        }

        // Transfer transient values to persistent ones
        persistentSession.copy(transientSession);
        
        setSaveSelected(true);
        setVisible(false);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel absoluteHoursPanel;
    private javax.swing.JLabel adjustmentDateLabel;
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextField comment;
    private javax.swing.JLabel commentLabel;
    private com.toedter.calendar.JDateChooser date;
    private TimeRecording.widgets.DateConverter dateConverter;
    private javax.swing.JComboBox employee;
    private javax.swing.JLabel employeeLabel;
    private TimeRecording.widgets.TimeTextField endTime;
    private javax.swing.JLabel endTimeLabel;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JPanel holidayRequestDetails;
    private javax.swing.JTextField hours;
    private javax.swing.JLabel hoursLabel;
    private javax.swing.JPanel hoursOrTimeFramePanel;
    private javax.swing.JPanel hoursOrTimeSelectionPanel;
    private javax.swing.JRadioButton numberOfHoursRadioButton;
    private javax.swing.JButton saveButton;
    private TimeRecording.widgets.TimeTextField startTime;
    private javax.swing.JLabel startTimeLabel;
    private javax.swing.JPanel timeFramePanel;
    private javax.swing.JRadioButton timeFrameRadioButton;
    private javax.swing.ButtonGroup timeSpecificationGroup;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    private SessionsDialog myParent;
}